using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Com.Easywiki.Model;
using Com.Easywiki.DAO;
using Common.Logging;

namespace Com.Easywiki.Controllers
{
	[HandleError]
	public class AdminController : Controller
	{		
		ILog log = LogManager.GetLogger("Ravi");
		
		private ICategoryDAO categoryDAO;
		public ICategoryDAO CatDAO	{
			get{
				log.Debug(" get CAt #####->" + this.categoryDAO);
				return this.categoryDAO;
			}
			set{
				log.Debug(" set Cat  #####->" + value);
				this.categoryDAO = value;
			}
		}

		private IUserDAO userDAO;
		public IUserDAO UDAO	{
			get{
				log.Debug(" get user #####->" + this.userDAO);
				return this.userDAO;
			}
			set{
				log.Debug(" set user  #####->" + value);
				this.userDAO = value;
			}
		}
		
		public ActionResult Index (){
			return View ("LogOn");
		}
		
		public ActionResult LogOn (){
			return View ();
		}
		
		[HttpPost]
		public ActionResult LogOn (LogOnModel model, string returnUrl){
			if (ModelState.IsValid) {
				Console.WriteLine (ModelState.IsValid);
				if(UDAO.LoginCheck(model.UserName,model.Password)){
					 FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
					if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
	                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) {
	                    return Redirect(returnUrl);
	                } else {
	                    return RedirectToAction("Dashboard");
	                }
				}else{
                	
					ModelState.AddModelError("", "The user name or password provided is incorrect.");
            	}
			}
			return View (model);
		}

		public ActionResult LogOut() {
            FormsAuthentication.SignOut();
            return RedirectToAction("LogOn");
        }

		[Authorize]
		public ActionResult Dashboard (){
			return View ();
		}

		[Authorize]
		public ActionResult Category (){
//			log.Debug("#####->" + CatDAO);
//			IList<Category> CategoryList =  CatDAO.LoadAllCategory();
//			log.Debug("#####->" + CategoryList);
//			ViewData ["CategoryList"] = CategoryList;
			return View ();
		}

		[Authorize]
		[HttpPost]
		public ActionResult Category (CategoryModel model){
			if (ModelState.IsValid) {
				Console.WriteLine("Saving Category");
				Category cat = new Category();
				cat.IsRoot = model.IsRoot;
				cat.Lable = model.Lable;
				cat.Link = model.Link;
				cat.ParentId = model.ParentId;
				Console.WriteLine(cat);
				CatDAO.Save(cat);
			}
			return View (model);
		}

	}
}

